package cn.tedu.sp06.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.pojo.Order;
import cn.tedu.sp01.pojo.User;
import cn.tedu.web.util.JsonResult;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@Slf4j
public class RibbonController {
  @Autowired
  private RestTemplate restTemplate;
  //调用商品服务
  @GetMapping("/item-service/{orderId}")
  @HystrixCommand(fallbackMethod = "getItemsSB")
  public JsonResult<List<Item>> getItems(@PathVariable String orderId) {
    // 调用远程的商品服务，获取商品列表
    return restTemplate.getForObject("http://item-service/{1}", JsonResult.class, orderId);
  }
  @PostMapping("/item-service/decreaseNumber")
  @HystrixCommand(fallbackMethod = "decreaseNumberSB")
  public JsonResult<?> decreaseNumber(@RequestBody List<Item> items) {
    return restTemplate.postForObject("http://item-service/decreaseNumber",items,JsonResult.class);
  }
  //调用用户
  @GetMapping("/user-service/{userId}")
  @HystrixCommand(fallbackMethod = "getUserSB")
  public JsonResult<User> getUser(@PathVariable Integer userId){
    return restTemplate.getForObject("http://user-service/{1}",JsonResult.class,userId);
  }
  @GetMapping("/user-service/{userId}/score")
  @HystrixCommand(fallbackMethod = " addScoreSB")
  public JsonResult<User> addScore(@PathVariable Integer userId,Integer score){
    return restTemplate.getForObject("http://user-service/{1}/score?score={2}",JsonResult.class,userId,score);
  }
  //调用订单
  @GetMapping("/order-service/{orderId}")
  @HystrixCommand(fallbackMethod = "getOrderSB")
  public JsonResult<Order> getOrder(@PathVariable String orderId){
    return restTemplate.getForObject("http://order-service/{1}",JsonResult.class,orderId);
  }
  @GetMapping("/order-service")
  @HystrixCommand(fallbackMethod = "saveOrderSB")
  public JsonResult<?> saveOrder(){
    return restTemplate.getForObject("http://order-service",JsonResult.class);

  }

/**************************************************************************************/
  public JsonResult<List<Item>> getItemsSB( String orderId) {
    /**
     * 1 错误提示
     * 2 缓存数据
     * 3 根据业务逻辑返回任意内容
     */
    return JsonResult.err().msg("getItemsSB调用失败");
  }
  public JsonResult<?> decreaseNumberSB(List<Item> items) {
    return JsonResult.err().msg("decreaseNumberSB调用失败");
  }
  //调用用户
  public JsonResult<User> getUserSB( Integer userId){
    return JsonResult.err().msg("getUserSB调用失败");
  }
  public JsonResult<User> addScoreSB(Integer userId,Integer score){
    return JsonResult.err().msg("addScoreSB调用失败");
  }
  //调用订单
  public JsonResult<Order> getOrderSB( String orderId){
    return JsonResult.err().msg("getOrderSB调用失败");
  }
  public JsonResult<?> saveOrderSB(){
    return JsonResult.err().msg("saveOrderSB调用失败");

  }
}
